package net.wanho.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.bcel.internal.generic.RETURN;

import java.util.Calendar;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    private static final String SECRET = "wanho";

    /**
     * 生成令牌
     * @param payload
     * @return
     */
    public static String generate(Map<String, Object> payload){
         Calendar c = Calendar.getInstance();
         c.add(Calendar.HOUR, 12);

         String token = JWT.create()
                 .withPayload(payload) // 载荷
                 .withExpiresAt(c.getTime()) // 过期时间
                 .sign(Algorithm.HMAC256(SECRET)); //  签名算法和密钥
         return token;
    }

    /**
     * 校验令牌
     */
    public static boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 解析令牌
     */
    public static Integer parseInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static String parseString(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }

}
